﻿
+function ($) {
    if (!window.plutostudio) {
        window.plutostudio = function () { }
    }

    
    'use strict';
    var defaults = {
        newModel: {},
        title: '',
        action: '',
        columns: [],
        allowAdd: true,
        customCommand: {},
        modelTitle:'',
        querystring:''
    }

    var Service = function (options) {
        this.options = $.extend(true, {}, defaults, options);
        var modelDefine = function ($this) {
            this.model = ko.observable(ko.mapping.fromJS($this.options.newModel))
        }
        $.ajaxSetup({
            cache:false
        })
        this.model = new modelDefine(this);
    }

    Service.prototype.init = function () {
        $('#EditModal').data('modal', null)
        this._initTable()
        this._initModal()
        return this;
    }

    Service.prototype._initTable = function () {
        var $this = this;
        var $table = $('.table').dataTable({
            "sDom": "<'row'<'col-sm-12'<'col-sm-8 left-side'>f>r>t<'row'<'col-sm-6' i><'col-sm-6'p>>",
            "ordering": false,
            "bServerSide": true,
            "bProcessing": true,
            "bStateSave": false,
            "ajax": this.options.action + "/List"+this.options.querystring,
            "columnDefs": this.options.columns
        }).on('command.edit.dt', function (e, s, d) {
            $this.model.model(ko.observable(ko.mapping.fromJS(d.data)));
            $('#EditModal').modal({
                remote: $this.options.action+'/Edit',
                title: '编辑' + $this.options.title
            });
        }).on('command.delete.dt', function (e, s, d) {
            bootbox.confirm({
                message: '您是否真的要删除' + $this.options.title + '：' + d.data[$this.options.modelTitle],
                title: "删除确认",
                buttons: {
                    confirm: { label: '确定' },
                    cancel: { label: '取消' }
                },
                callback: function (result) {
                    if (result) {
                        $.ajax({cache:false,url: $this.options.action + '/Delete/' + d.data.id,success: function (r) {
                            $('.table').dataTable()._fnAjaxUpdate()
                        }});
                    }
                }
            });
        });
        for (var i in this.options.customCommand) {
            $table.on(i, this.options.customCommand[i])
        }
        if (this.options.allowAdd) {
            $('<a class="btn btn-success btn-sm add-entity" data-toggle="modal" data-title="添加' + $this.options.title + '" data-target="#EditModal" href="/' + $this.options.action + '/Edit" style="margin-bottom: 10px">添加' + $this.options.title + '</a>').appendTo('.left-side');
        }
    }

    Service.prototype._initModal = function () {
        var $this = this;
        $('#EditModal').off('save.command.bs.modal')
        var $btn;
        $('#EditModal').on('save.command.bs.modal', function (e) {
            $btn = $(e.button).button('loading')
            $('#EditModal').on('hide.bs.modal', function () { return false; })
            $(document).one('success.bs.form', '#edit-form', function () {
                $btn.button('reset')
                $('#EditModal').off('hide.bs.modal')
                $('#EditModal').modal('hide');
                $('.table').dataTable()._fnAjaxUpdate()
            })
            $(document).one('error.bs.form', '#edit-form', function (e) {
                $btn.button('reset')
                $('#EditModal').off('hide.bs.modal')
            })
            $('#edit-form').submit();
        }).on('loaded.bs.modal', function (e) {
            ko.applyBindings($this.model, $('#edit-form')[0]);
            $.validator.init({
                invalidHandler: function (form) {
                    $(document).off('error.bs.form', '#edit-form');
                    $(document).off('success.bs.form', '#edit-form');
                    $btn.button('reset')
                    $('#EditModal').off('hide.bs.modal')
                }
            });

        }).on('show.bs.modal', function (e) {
            var target = $(e.relatedTarget)
            if (target.hasClass('add-entity')) {
                $this.model.model(ko.observable(ko.mapping.fromJS($this.options.newModel)));
            }
        })
        $('#EditModal').on('shown.bs.modal', function () {
            $('.chosen-select').chosen({ allow_single_deselect: true });
        })
    }
    
    plutostudio.service = function (options) { return new Service(options) };
    plutostudio.service.constructor = Service;
}(jQuery)

